package xiaolong.lian.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import xiaolong.lian.entity.Page;
import xiaolong.lian.exception.CustomException;
import xiaolong.lian.service.PageService;
import xiaolong.lian.util.Args;
import xiaolong.lian.util.Cookies;

import java.io.IOException;

@Controller
@RequestMapping("/page")
public class PageController {
    @Autowired
    private PageService pageService;

    @RequestMapping(value = "/list" , method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getPages(String docId) throws CustomException {
        new Args().ensureNotEmpty("文档id", docId);
        return pageService.getPageList(docId, Cookies.get("tel")).toString();
    }

    @RequestMapping(value = "/create" , method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public String create(String docId, Integer num) throws CustomException {
        new Args().ensureNotEmpty("文档id", docId);
        if(num == null || num < 1)
            throw new CustomException("无效的页号");
        Page page = pageService.createPage(docId, num, Cookies.get("tel"));
        return page.toString();
    }

    @RequestMapping(value = "/delete" , method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public String delete(String id) throws CustomException {
        new Args().ensureNotEmpty("页面id", id);
        pageService.deletePage(id, Cookies.get("tel"));
        return "{\"msg\" : \"删除页面成功\"}";
    }

    @RequestMapping(value = "/update" , method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public String update(String id, String data) throws CustomException, IOException {
        new Args().ensureNotEmpty("页面id", id);
        if(data == null)
            data = "";
        pageService.updatePageData(id, data, Cookies.get("tel"));
        return "{\"msg\" : \"保存页面成功\"}";
    }

    @RequestMapping(value = "/data" , method = RequestMethod.GET, produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String data(String id) throws IOException {
        new Args().ensureNotEmpty("页面id", id);
        return pageService.getPageData(id, Cookies.get("tel"));
    }
}
